#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import socket
import time

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s')
LOG = logging.getLogger('server')


def handle_request(client):
    LOG.debug('waiting data...')
    buf = client.recv(1024)
    LOG.debug('recv: %r', buf)
    LOG.debug('responcing...')
    client.send("HTTP/1.1 200 OK\r\n\r\n")
    LOG.debug('responced.')
    time.sleep(0.1)
    LOG.debug('responcing...')
    client.send("Hello World")
    LOG.debug('responced. over.')


def main(is_ready=None, running=None):
    host = 'localhost'
    port = 8000
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while True:
        try:
            sock.bind((host, port))
            LOG.warning('bind %s:%s ok', host, port)
            break
        except Exception as error:
            LOG.warning('bind %s:%s error: %s', host, port, error)
            time.sleep(1)
    LOG.debug('runing at %s:%s', host, port)
    sock.listen(10)
    sock.settimeout(1)

    if is_ready is not None:
        is_ready.value = True

    while True if running is None else running.value:
        LOG.debug('waiting for a client')
        try:
            connection, address = sock.accept()
        except socket.timeout:
            LOG.debug('timeout')
            continue
        LOG.debug('got a connection: %r, %r', connection, address)
        LOG.debug('handling...')
        handle_request(connection)
        LOG.debug('handled.')
        try:
            connection.close()
        except Exception as error:
            LOG.warning('got exception when closing connection: %s', error)
        finally:
            LOG.debug('connection closed.')

    sock.close()


if __name__ == '__main__':
    main()
